// 用户相关
import { defineStore } from "pinia";
// 引入接口
import { reqFindPassword, reqLogin, reqValidateEmailCode, sendEmailCaptcha } from "@/api/user";
// 引入数据类型
import type { findPasswordReq, findePasswordRes, loginForm, loginResponseData, sendEmail, validateEmailCodeRes } from "@/api/user/type";
import type { UserState } from '@/stores/modules/types/type'
import { SET_TOKEN, GET_TOKEN } from '@/utils/token'

//引入常量路由
import {constantRouter} from '@/router/menu'
import { ElMessage } from "element-plus";

let useUserStore = defineStore('User', {
    state: ():UserState => {
        return {
            token: GET_TOKEN() || '',
            menuRoutes: constantRouter //仓库存储所有路由路径
        }
    },
    actions: {
        // 登录方法
        async userLogin(data: loginForm) {
            //发送请求
            let result:loginResponseData = await reqLogin(data)
            if (result.code == 200) {
                // 存储token
                this.token = (result.data.token as string)
                SET_TOKEN(result.data.token as string)
                return 'ok'
            }else {
                // console.log(Promise.reject(new Error(result.data.messge)));
                
                return Promise.reject(new Error(result.data.message ))
            }
        },
        //获取验证码
        async getCaptcha(data: sendEmail){
            let result: sendEmailResponse = await sendEmailCaptcha(data)
            if(result.code == 200 ) {
                console.log('验证码发送成功');
                
                return result.data.data.key
            }else {
                return Promise.reject(new Error(result.data.message))
            }
        },

        // 验证邮箱验证码是否正确
        async  validateEmailCode(data:validateEmailCodeReq ) {
            let result: validateEmailCodeRes = await reqValidateEmailCode(data)
            if(result.code == 200 ) {
                console.log( result.data.message);
                return true
            } else {
                return Promise.reject(new Error(result.message))
            }
        },
        async findePassword(data: findPasswordReq){
            
            let result: findePasswordRes =await reqFindPassword(data)
            if(result.code == 200) {
                ElMessage({
                    message: '密码找回成功！',
                    type: 'success',
                  })
            } else {
                return Promise.reject(new Error(result.data.message[0]))//待处理
            }
        }
    },
    getters: {

    },
// token本地持久化 也可以：localStorage.setItem("TOKEN", this.token)
    // persist: true,
},)

 
// 对外暴露获取仓库方法
export default useUserStore;